<template>
	<view class="wrap">
		<div v-for="(item,index) in form.fileList" class="event-banner" v-if="form.fileList" :key="index">
			<u-image width="100%" height="100%" :src="item.url"></u-image>
		</div>
		<div v-if="form.fileList.length<= 0">
			<u-upload ref="uUpload" :file-list="form.fileList" :before-upload="beforeUpload" :auto-upload="false"
				:show-tips="false" @on-choose-complete="choose" max-count="1"></u-upload>
		</div>
		<!-- 		<div>
			<button type="primary" plain @click="up">上传</button>
		</div> -->
		<div class="flex-auto overflow-auto h-10 p-4 bg-white my-2">
			<div style="border:1px solid #F29100" v-if="false">
				id:{{aId}}
				<!-- <m-qrcode cid="qrcode" ref="qrcode" val="http://zmp.igiky.cn/event/event?id=609b99029abec80001e118f0"
					:size="400" :loadMake="true"></m-qrcode> -->
				<m-qrcode cid="qrcode" ref="qrcode" :val="'http://zmp.igiky.cn/event/event?id='+aId" :size="200"
					:loadMake="true"></m-qrcode>
			</div>
			<u-form :model="form" ref="uForm" :label-width="200" :label-style="labelStyle">
				<u-input v-model="form.id" v-show="false" />
				<u-form-item label="活动名称">
					<u-input v-model="form.name" v-if="formEdit" />
					<span v-if="!formEdit">{{form.name}}</span>
				</u-form-item>
				<u-form-item label="开始时间">
					<span v-if="!formEdit">{{start_date_text}}</span>
					<div class="w-full" v-if="formEdit">
						<u-input v-model="form.start_date" v-show="false" />
						<u-input v-model="start_date_text" @click="start_date_show=true" disabled type="select" />
						<u-picker mode="time" v-model="start_date_show" :params="params" @confirm="startTimeConfirm">
						</u-picker>
					</div>
				</u-form-item>
				<u-form-item label="结束时间">
					<span v-if="!formEdit">{{end_date_text}}</span>
					<div class="w-full" v-if="formEdit">
						<u-input v-model="form.end_date" v-show="false" />
						<u-input v-model="end_date_text" @click="end_date_show=true" disabled type="select" />
						<u-picker mode="time" v-model="end_date_show" :params="params" @confirm="endTimeConfirm">
						</u-picker>
					</div>
				</u-form-item>
				<u-form-item label="地址">
					<span v-if="!formEdit">{{form.address}}</span>
					<u-input v-if="formEdit" v-model="form.address" />
				</u-form-item>
				<u-form-item label="活动介绍">
					<span v-if="!formEdit">{{form.info}}</span>
					<u-input v-if="formEdit" type="textarea" v-model="form.info" />
				</u-form-item>
			</u-form>
			<u-cell-group>
				<u-cell-item icon="integral-fill" :title="item.username" :value="$utils.timestampToTime(item.sign_date)"
					:arrow="false" v-for="(item,index) in signList" :key="index"></u-cell-item>
			</u-cell-group>

		</div>
		<div class="px-2 mb-2">
			<u-button v-if="!formEdit" type="primary" @click="signIn" :loading="btnLoading" :disabled="signInDis">{{signInText}}
			</u-button>
			<u-button v-if="formEdit" type="primary" @click="save" :loading="btnLoading">保存活动</u-button>
		</div>
		<m-tab-bar></m-tab-bar>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		getQueryString
	} from '@/common/utils.js'
	export default {
		data() {
			return {

				form: {
					action: "save",
					name: "",
					create_date: Date.now(),
					start_date: '',
					end_date: '',
					address: "",
					info: "",
					fileList: []
				},
				signList: [],
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				start_date_show: false,
				end_date_show: false,
				start_date_text: '',
				end_date_text: '',
				btnLoading: false,
				aId: '',
				signInText: '签到',
				signInDis: false,
				formEdit: false,
				headStyle: {
					borderBottom: '1px solid #eee',
					paddingLeft: '10rpx',
					fontWeight: 'bold'
				},
				bodyStyle: {
					padding: '0 10rpx'
				},
				labelStyle:{
					fontWeight: 'bold'
				}
			}
		},
		watch: {
			form: { //深度监听，可监听到对象、数组的变化
				handler(val, oldVal) {
					if (this.form.start_date || this.form.end_date) {
						this.start_date_text = this.$utils.timestampToTime(this.form.start_date)
						this.end_date_text = this.$utils.timestampToTime(this.form.end_date)
					}

				},
				deep: true //true 深度监听
			}
		},
		computed: mapState(['eventId']),
		onLoad(obj) {
			console.log(2,this.$utils)
			let id = obj.id ? obj.id : getQueryString(obj.q, 'id')
			if(id){
				this.aId = id
				this.getData(id)
				this.setEventId(id)
				this.isSignIn()
			}else{
				this.formEdit =true
			}
			
		},
		methods: {
			...mapMutations(['setEventId']),
			signIn() {
				this.btnLoading = true
				this.$reqFun.req("signin", {
					action: 'add',
					eid: this.aId,
					uid: uni.getStorageSync('user_id')
				}).then(res => {
					console.log(55, res)
					this.btnLoading = false
					this.signInText = '已签到'
					this.signInDis = true,
						this.getSigninList()
					// uni.hideLoading()
					// this.signList = res.result.data
				})
			},
			getData(id) {
				uni.showLoading({
					title: '加载中...'
				})
				this.$reqFun.req("events", {
					action: 'view',
					id: id
				}).then(res => {
					uni.hideLoading()
					this.form = {
						...this.form,
						...res.result.data[0]
					}
					this.form.id = res.result.data[0]._id
					delete this.form._id
				})
				this.getSigninList()
				// uniCloud.callFunction({
				// 	name: "events",
				// 	data: {
				// 		action: 'view',
				// 		id: id
				// 	},
				// 	success: (res) => {
				// 		uni.hideLoading()
				// 		this.form = res.result.data[0]
				// 		this.form.id = res.result.data[0]._id
				// 		delete this.form._id
				// 		console.log(res)
				// 	},
				// 	fail: (err) => {
				// 		uni.hideLoading()
				// 		console.log(err)
				// 	}
				// })
			},
			isSignIn(uid) {
				uniCloud.callFunction({
					name: "signin",
					data: {
						action: 'isSignIn',
						eid: this.aId,
						uid: uni.getStorageSync('user_id')
					},
					success: (res) => {
						if (res.result.data.length > 0) {
							// this.btnLoading = true
							this.signInText = '已签到',
								this.signInDis = true
						}
					},
					fail: (err) => {
						console.log(22222, err)
					},
				})
			},
			getSigninList() {
				this.$reqFun.req("events", {
					action: 'signlist',
					id: this.aId,
				}).then(res => {
					uni.hideLoading()
					console.log(222,this.aId,res.result.data)
					this.signList = res.result.data
				})
			},
			save() {
				this.btnLoading = true
				this.$reqFun.req("events", this.form).then(res => {
					this.btnLoading = false
					// uni.navigateBack()
					uni.reLaunch({
						url: '/pages/events/events'
					})
				})
				// uniCloud.callFunction({
				// 	name: "events",
				// 	data: this.form,
				// 	success: (res) => {
				// 		console.log(res)
				// 		this.btnLoading = false
				// 		uni.navigateBack()
				// 	},
				// 	fail: (err) => {
				// 		console.log(err)
				// 	}
				// })
			},
			startTimeConfirm(e) {
				// var date= new Date(e.year+"-"+e.month+"-"+e.day+"-"+e.hour+"-"+e.minute+"-"+e.second)
				var date = e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute + ":" + e.second
				var time1 = new Date(date).getTime();
				// console.log(22, this.timestampToTime(this.form.start_date))
				this.form.start_date = time1
				// console.log(22, this.timestampToTime(this.form.start_date))
			},
			endTimeConfirm(e) {
				var date = e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute + ":" + e.second
				var time1 = new Date(date).getTime();
				this.form.end_date = time1
				// this.form.end_date_text = this.timestampToTime(this.form.end_date)
			},

			choose(lists, name) {
				console.log(333, lists, name)
				let tImg = lists[0].url
				this.uploadByuView(tImg)
			},
			up() {
				console.log(222)
				this.$refs.uUpload.upload();
			},
			beforeUpload(index, list) {
				// 只上传偶数索引的文件
				console.log(123, index, list)
			},
			uploadByuView(tImg) {
				new Promise((resolve, reject) => {
					const path = tImg
					console.log(1, path)
					let ext
					// #ifdef H5
					// ext = res.tempFiles[0].name.split('.').pop()
					const options = {
						filePath: path,
						cloudPath: Date.now() + '.' + 'jpg'
					}
					// console.log(222)
					resolve(options)
					// #endif
					// #ifndef H5
					uni.getImageInfo({
						src: path,
						success(info) {
							const options = {
								filePath: path,
								cloudPath: Date.now() + '.' + info.type
									.toLowerCase()
							}
							resolve(options)
						},
						fail(err) {
							reject(new Error(err.errMsg || '未能获取图片类型'))
						}
					})
					// #endif
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
						}
					})
				}).then(res => {
					uni.hideLoading()
					this.form.fileList.push({
						url: res.fileID
					})
					console.log(res);
					// uni.showModal({
					// 	content: '图片上传成功，fileId为：' + res.fileID,
					// 	showCancel: false
					// })
				}).catch((err) => {
					uni.hideLoading()
					console.log(err);
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败，错误信息为：${err.message}`,
							showCancel: false
						})
					}
				})
			},
			upload() {
				new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						success: res => {
							const path = res.tempFilePaths[0]
							console.log(1, path)
							let ext
							// #ifdef H5
							ext = res.tempFiles[0].name.split('.').pop()
							const options = {
								filePath: path,
								cloudPath: Date.now() + '.' + ext
							}
							resolve(options)
							// #endif
							// #ifndef H5
							uni.getImageInfo({
								src: path,
								success(info) {
									const options = {
										filePath: path,
										cloudPath: Date.now() + '.' + info.type
											.toLowerCase()
									}
									resolve(options)
								},
								fail(err) {
									reject(new Error(err.errMsg || '未能获取图片类型'))
								}
							})
							// #endif
						},
						fail: () => {
							reject(new Error('Fail_Cancel'))
						}
					})
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
						}
					})
				}).then(res => {
					uni.hideLoading()
					console.log(res);
					uni.showModal({
						content: '图片上传成功，fileId为：' + res.fileID,
						showCancel: false
					})
				}).catch((err) => {
					uni.hideLoading()
					console.log(err);
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败，错误信息为：${err.message}`,
							showCancel: false
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "./events.scss";
</style>
